<?php
namespace App\Http\Controllers\www;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Http\Controllers\Weixin\WeixinServiceController;

class DidiController extends Controller
{

    public $apiList = array(
        "chooseImage",
        "onMenuShareTimeline",
        "onMenuShareAppMessage",
        "onMenuShareQQ",
        "onMenuShareWeibo",
        "previewImage",
        "uploadImage",
        "downloadImage",
        "startRecord",
        "stopRecord",
        "onVoiceRecordEnd",
        "playVoice",
        "pauseVoice",
        "stopVoice",
        "translateVoice",
        "onVoicePlayEnd",
        "uploadVoice",
        "downloadVoice",
        "hideOptionMenu",
        "showOptionMenu",
        "closeWindow",
        "hideMenuItems",
        "showMenuItems",
        "scanQRCode",
        "chooseWXPay");


    public function index(Request $request)
    {
        $weixinController = new WeixinServiceController();
        $weixinApp = $weixinController->get_weixin_app();
        $weixinJs = $weixinApp->js;

        $config = $weixinJs->config(array('onMenuShareAppMessage', 'onMenuShareTimeline'), false,false,false);
        //$config = $weixinJs->config(array('onMenuShareAppMessage', 'onMenuShareTimeline'), false);
        $host   = $request->getHost();
        return view('www/didi/index',['weixinJs'=>$config,'host'=>$host]);

    }

    public function action(Request $request,$action){
        header('Access-Control-Allow-Origin:*');
        return $this->$action($request);
    }


    public function saveData(Request $request)
    {
        header('Access-Control-Allow-Origin:*');

        $data   = [

            'name'  => $request->input('name'),
            'grade' => $request->input('grade'),
            'flag'  => $request->input('flag'),
            'user_id'=>$request->input('userId'),
            'sex'   => $request->input('sex',''),
            'add_time'      => date_time(),
            'address'       => $request->input('address'),
            'finish_date'   => $request->input('time'),
            'latitude'      => $request->input('latitude'),
            'longitude'     => $request->input('longitude')
        ];
        if($request->input('latitude'))
        {
            $data['address'] =  $this->jwtoaddress($data['latitude'],$data['longitude']);
        }
        $id = DB::table('dd_flag')->insertGetId($data);
        return response()->json(['id'=>$id]);
        return response()->json($request->all());
    }


    public function get_address()
    {
        //$url = "http://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=76KBZ-27IWD-PSC4Z-HXFA6-PNJJ3-LYBZ5
        $flag = false;
        $id = 0;
        do{
            if($flag)
            {
                $id         = $flag->id;
                $address    = $this->jwtoaddress($flag->latitude,$flag->longitude);
                DB::table('dd_flag')->where('id',$id)->update(['address'=>$address]);
            }
            $flag = DB::table('dd_flag')
                ->where('id',">",$id)
                ->where('latitude',"<>",0)
                ->where('latitude',"<>","")
                ->where('address')
                ->first();
            if(!$flag)
            {
                exit();
            }
            sleep(1);
        }while($flag);
    }

    private function jwtoaddress($latitude,$longitude)
    {
        $address = "";
        $key    = "FX4BZ-5BJ3F-K6BJA-NOWBR-VX2Z6-H4BVG";
        $url = "http://apis.map.qq.com/ws/geocoder/v1/?location={$latitude},{$longitude}&key={$key}";
        $content = file_get_contents($url);
        $content = \GuzzleHttp\json_decode($content);
        if($content->status == 0)
        {
            $result = $content->result;

            if($result->address){
                $address = $result->address;
            }
        }
        return $address;
    }
    //自己查看的界面
    public function selfFlag(Request $request)
    {

        if($this->is_weixin()) {
            $wxInfo = $this->wxenter($request);
            $openId = $wxInfo['id'];
        }else {

            $openId = create_member_number();
            //$openId = "201803221842954143";
        }

        $dir    = public_path("images/didi/");
        $id     = $request->input('flagId',0);


        $flagInfo = DB::table('dd_flag')->where('id',$id)->first();
        if(!$flagInfo)
        {
            return "<script>alert('没有内容')</script>";
        }

        $left   = 195;
        $top    = 350;
        $size   = 24;
        $lineHeight = 76;
        $font   = $dir."zhunjian.ttf";


        $str    = $flagInfo->flag;
        //$str    = "导开导";
        $lineLength = 11;
        $i = 0;
        $texts = [""];
        $maxwidth = 360;

        $textLength = mb_strlen($str);
        while($i < $textLength){

            $t   = mb_substr($str,$i,1);
            $key = count($texts);

            $t1   = $texts[$key -1] . $t;
            $textInfo   = imagettfbbox($size,0,$font,$t1);
            if($textInfo[4]<$maxwidth)
            {
                $texts[$key -1] = $t1;
            }else{
                $texts[$key] = $t;
            }
            $i++;
        }

        
        if(count($texts) < 4)
        {
            $bgimg      = $dir."template1.jpg";
            $timeTop    = 600;
        }else{
            $bgimg      = $dir."template.jpg";
            $timeTop    = 840;
        }


        $bgsrc  = imagecreatefromjpeg($bgimg);

        $endImg = $dir."shareimg/{$id}.jpg";
        $whiteColor  = imagecolorallocate($bgsrc,255,255,255);
       



        //1.写标题
        $title  = "{$flagInfo->name}的新学期FLAG";
        $titleLeft  = 90 + (578 - imagettfbbox($size + 5, 0, $font, $title)[4])/2 ;
        imagettftext($bgsrc,$size+5,0,$titleLeft,$top-80,$whiteColor,$font,$title);

        //2.写内容
        $blueColor  = imagecolorallocate($bgsrc,212,236,255);
        $lineNumber = count($texts);

        foreach($texts as $key => $text)
        {
            if($key > 5)
            {
                break;
            }

            if($lineNumber > 0)
            {
                imagettftext($bgsrc,$size,0,$left,$top,$blueColor,$font,$text);         
            }else{
                $tempLeft   = $left + ($maxwidth - imagettfbbox($size, 0, $font, $text)[4])/2;
                imagettftext($bgsrc,$size,0,$tempLeft,$top,$blueColor,$font,$text);         
            }
           
           $top = $top + $lineHeight;
        }

        //3.写完成时间
        $date   = str_replace("-",".",$flagInfo->finish_date);
        imagettftext($bgsrc,$size-2,0,$left+30,$timeTop,$whiteColor,$font,"完成时间");
        imagettftext($bgsrc,$size-2,0,$left+160,$timeTop,$blueColor,$font,$date);

        imagejpeg($bgsrc,$endImg);
        
        $host   = $request->getHost();

        //获取前10的内容
        $flags = DB::table('dd_flag as a')
            ->select("a.*","b.zan_id")
            ->leftJoin('dd_zan as b','b.id','=',DB::raw('a.id AND b.type = "flag" AND open_id = "'.$openId.'"'))
            ->orderBy('a.zan_number','desc')
            ->limit(10)
            ->get();


        $weixinController = new WeixinServiceController();
        $weixinApp = $weixinController->get_weixin_app();
        $weixinJs = $weixinApp->js;
        $data   = [
            'flags'     => $flags,
            'host'      => $host,
            'flagInfo'  => $flagInfo,
            'openId'    => $openId,
            "weixinJs"  => $weixinJs,
            "apiList"   => $this->apiList,
            'shareData' => $this->getShareData($flagInfo->name)
        ];

        return view('www/didi/self-flag',$data);

    }


    public function create_image($id)
    {

        $dir        = public_path("images/didi/");
        $endImg     = $dir."shareimg/{$id}.jpg";
        $imagefile  = "http://".request()->getHost()."/images/didi/shareimg/{$id}.jpg";
        if(file_exists($endImg)){

            return $imagefile;
        }

        $flagInfo = DB::table('dd_flag')->where('id',$id)->first();
        $left   = 195;
        $top    = 350;
        $size   = 24;
        $lineHeight = 76;
        $font   = $dir."zhunjian.ttf";

        //$str    = "导开导";
        $str    = $flagInfo->flag;
        $i = 0;
        $texts = [""];
        $maxwidth = 360;

        $textLength = mb_strlen($str);
        while($i < $textLength){

            $t   = mb_substr($str,$i,1);
            $key = count($texts);

            $t1   = $texts[$key -1] . $t;
            $textInfo   = imagettfbbox($size,0,$font,$t1);
            if($textInfo[4]<$maxwidth)
            {
                $texts[$key -1] = $t1;
            }else{
                $texts[$key] = $t;
            }
            $i++;
        }


        if(count($texts) < 4)
        {
            $bgimg      = $dir."template1.jpg";
            $timeTop    = 600;
        }else{
            $bgimg      = $dir."template.jpg";
            $timeTop    = 840;
        }


        $bgsrc  = imagecreatefromjpeg($bgimg);

        $endImg = $dir."shareimg/{$id}.jpg";
        $whiteColor  = imagecolorallocate($bgsrc,255,255,255);




        //1.写标题
        $title  = "{$flagInfo->name}的新学期FLAG";
        $titleLeft  = 90 + (578 - imagettfbbox($size + 5, 0, $font, $title)[4])/2 ;
        imagettftext($bgsrc,$size+5,0,$titleLeft,$top-80,$whiteColor,$font,$title);

        //2.写内容
        $blueColor  = imagecolorallocate($bgsrc,212,236,255);
        $lineNumber = count($texts);

        foreach($texts as $key => $text)
        {
            if($key > 5)
            {
                break;
            }

            if($lineNumber > 0)
            {
                imagettftext($bgsrc,$size,0,$left,$top,$blueColor,$font,$text);
            }else{
                $tempLeft   = $left + ($maxwidth - imagettfbbox($size, 0, $font, $text)[4])/2;
                imagettftext($bgsrc,$size,0,$tempLeft,$top,$blueColor,$font,$text);
            }

            $top = $top + $lineHeight;
        }

        //3.写完成时间
        $date   = str_replace("-",".",$flagInfo->finish_date);
        imagettftext($bgsrc,$size-2,0,$left+30,$timeTop,$whiteColor,$font,"完成时间");
        imagettftext($bgsrc,$size-2,0,$left+160,$timeTop,$blueColor,$font,$date);
        imagejpeg($bgsrc,$endImg);
        return $imagefile;
    }


    public function flagData(Request $request){

        $openId     = $request->input('openId');
        $flagId     = $request->input('flagId');

        $flagInfo   = DB::table('dd_flag')->where('id',$flagId)->first();
        $shareImg   = $this->create_image($flagId);

        //获取前10的内容
        $flags = DB::table('dd_flag as a')
            ->select("a.*",db::raw("IFNULL(b.zan_id,0)  zan_id"))
            ->leftJoin('dd_zan as b','b.id','=',DB::raw('a.id AND b.type = "flag" AND open_id = "'.$openId.'"'))
            ->orderBy('a.zan_number','desc')
            ->paginate(10);
        $flagInfo->image    = $shareImg;

        $data   = [
            'flags'     => $flags,
            'flagInfo'  => $flagInfo,
            'shareData' => $this->getShareData($flagInfo->name)
        ];
        return response($data);
    }




    public function zan(Request $request){
        header('Access-Control-Allow-Origin:*');
        $id     = $request->input('id');
        $type   = $request->input('type');
        $openId = $request->input('openId');

        if(!in_array($type,['flag','comment']))
        {
            return apiData()->send(201,"类型错误");
        }

        //检查用户是否对其点赞
        $zanInfo = DB::table('dd_zan')
            ->where('id',$id)
            ->where('type',$type)
            ->where('open_id',$openId)
            ->first();

        if($zanInfo)
        {
            return apiData()->send(202,"您已经点过赞");
        }

        $data   = [
            'id'        => $id,
            'type'      => $type,
            'open_id'   =>$openId,
            'add_time'  => date_time()
        ];
        DB::table('dd_zan')->insert($data);

        $tables = ['flag'=>"dd_flag","comment"=>"dd_comment"];
        $sql = "UPDATE $tables[$type] SET zan_number = zan_number + 1 WHERE id = $id";
        if($type == "comment")
        {
            $sql = "UPDATE $tables[$type] SET zan_number = zan_number + 1 WHERE comment_id = $id";
        }

        DB::update($sql);

        return apiData()->send(200,"");
    }



    public function addComment(Request $request)
    { header('Access-Control-Allow-Origin:*');
        $comment    = $request->input('comment');
        $openId     = $request->input('openId');
        $flagId     = $request->input('flagId');


        $data   = [
            'id'            => $flagId,
            'zan_number'    => 0,
            'content'       => $comment,
            'user'          => $openId,
            'add_time'      => date_time()
        ];

        $id = DB::table('dd_comment')->insertGetId($data);

        return apiData()->set_data('id',$id)->send(200,'ok');

    }


    public function commentFlag(Request $request)
    {

        if($this->is_weixin()) {
            $wxInfo = $this->wxenter($request);
            $openId = $wxInfo['id'];
        }else {

            $openId = create_member_number();
            //$openId = "201803221842954143";
        }


        $flagId = $request->input('id');
        $sql = "SELECT a.*,b.zan_id FROM dd_flag a
                LEFT JOIN dd_zan b ON  b.id=a.id
                      AND b.type = 'flag'
                      AND b.open_id = '{$openId}'
                WHERE a.id = $flagId limit 1";

        $flagInfo   = DB::select($sql);
        $flagInfo   = $flagInfo[0];


        $sql = "SELECT a.*,b.zan_id FROM dd_comment a
                LEFT JOIN dd_zan b ON b.id = a.comment_id
                          AND b.type    = 'comment'
                          AND b.open_id = '{$openId}'
                WHERE     a.id = $flagId
                ORDER BY a.zan_number DESC
                ";

        $comments   = DB::select($sql);

        $weixinController = new WeixinServiceController();
        $weixinApp  = $weixinController->get_weixin_app();
        //$didiH5Url  = system_log("didih5url");
        $didiH5Url      = "http://".$request->getHost()."/www/dd/index?openId=".$openId;

        $weixinJs = $weixinApp->js;
        $data   = [
            'flagInfo'      => $flagInfo,
            'host'          => $request->getHost(),
            'comments'      => $comments,
            'openId'        => $openId,
            "weixinJs"      => $weixinJs,
            "apiList"       => $this->apiList,
            'shareData'     => $this->getShareData($flagInfo->name),
            "h5Url"         => $didiH5Url
        ];

        return view('www/didi/comment-flag',$data);
    }



    public function commentData(Request $request)
    {

        $openId = $request->input('openId');
        $flagId = $request->input('flagId');

        $sql = "SELECT a.*,IFNULL(b.zan_id,0) zan_id FROM dd_flag a
                LEFT JOIN dd_zan b ON  b.id=a.id
                      AND b.type = 'flag'
                      AND b.open_id = '{$openId}'
                WHERE a.id = $flagId limit 1";

        $flagInfo   = DB::select($sql);
        $flagInfo   = $flagInfo[0];


        $sql = "SELECT a.*,IFNULL(b.zan_id,0) zan_id FROM dd_comment a
                LEFT JOIN dd_zan b ON b.id = a.comment_id
                          AND b.type    = 'comment'
                          AND b.open_id = '{$openId}'
                WHERE     a.id = $flagId
                ORDER BY a.zan_number DESC
                ";

        $comments   = DB::select($sql);
        $shareImg   = $this->create_image($flagId);

        $flagInfo->image    = $shareImg;
        $data   = [
            'flagInfo'      => $flagInfo,
            'comments'      => $comments,
            'shareData'     => $this->getShareData($flagInfo->name)
        ];

        return response($data);
    }



    //微信入口
    public function wxenter(Request $request)
    {

        $wx     = new WeixinServiceController();

        // 未登录
        $wechatUser     = $request->session()->get('wechat_user');
        if($wechatUser){
            return $wechatUser;
        }

        $callbackUrl    = "www/didi/callback";
        $oauth          = $wx->get_weixin_app(1, $callbackUrl)->oauth;
        $targetUrl      = $request->getRequestUri();
        $oauth->state   = base64_encode($targetUrl);

        // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
        $oauth->redirect()->send();

    }



    public function callback(Request $request){

        $wx     = new WeixinServiceController();
        $oauth  = $wx->get_weixin_app(1)->oauth;
        $user = $oauth->user();

        $request->session()->put('wechat_user',$user->toArray());
        $request->session()->save();

        $targetUrl  = $request->input('state');
        $targetUrl  = base64_decode($targetUrl);
        return response()->redirectTo($targetUrl);
    }


    private  function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }



    public function h5enter(Request $request)
    {

        $url    = $request->input('url');
        $request->session()->put('h5url',$url);
        $request->session()->save();

        if($this->is_weixin()) {
            $wxInfo = $this->wxenter($request);
            $openId = $wxInfo['id'];
        }else {

            $openId = create_member_number();
        }

        $h5url  = $request->session()->get('h5url');
        if(!preg_match('/\?/',$h5url))
        {
            $h5url .= "?";
        }
        $h5url .= "&openId=".$openId;;

        return response()->redirectTo($h5url);
    }



    public function getShareData($name)
    {
        $shareData = [];
        $shareData[0]="{$name}的新学期flag竟然是…，不愧是嘴炮MAX！";
        $shareData[1]="{$name}的新学期flag竟然是……会被打脸吗？";
        $shareData[2]="呵呵，{$name}又立flag";
        $shareData[3]="呵呵，{$name}又立flag了 微笑.jpg";
        $shareData[4]="欢迎走进{$name}的打脸世界";
        $shareData[5]="打脸算什么，flag必须立！{$name}的新学期flag竟然是……";
        $shareData[6]="{$name}的新学期flag…谁不是一边立flag一边被打脸？";
        $shareData[7]="{$name}的新学期flag……静看打脸";
        $shareData[8]="{$name}的每一个新学期flag都是一粒沙，在朋友圈累积成了撒哈拉";
        $shareData[9]="那些新学期立flag的人后来都怎么样了？{$name}有话要说";
        $shareData[10]="{$name}的flag？呵呵";
        $shareData[11]="{$name}的flag？Know yourself.微笑.jpg";
        $shareData[12]="那些新学期立flag的人后来都怎么样了？看看{$name}就知道……";
        $key    = rand(0,12);
        return $shareData[$key];
    }



    /**
     * flag列表
     * */
    public function flags(Request $request)
    {

        $flags  = DB::table('dd_flag')->paginate(20);

        return view('www/didi/flags',['flags'=>$flags]);

    }

    public function deleteFlag(Request $request)
    {
        DB::table('dd_flag')->where('id',$request->flagId)->delete();
        return apiData()->notice('已删除');
    }


}
